﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

#region License
/*
 *  Copyright (c) Dumuzi.cn 2009 , All rights reserved.
 *  CLR Version: 2.0.50727.4927
 *  NameSpace: Summer.IO
 *  Author:Edwin Tai,戴佳顺
 *  Msn:edwin19861218@hotmail.com
 *  QQ: 1961218
 *  Date:2009-11-02 22:46:42
 *  Licensed under the Microsoft Public License (Ms-PL)
 *  This license governs use of the accompanying software. 
 *  If you use the software, you accept this license.
 *  If you do not accept the license, do not use the software.
 */
#endregion

namespace Summer.IO
{
    /// <summary>
    /// Xml file parser 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class XmlFileParser<T> : AbstractFileParser<T>
        where T:IParseableFile
    {
        /// <summary>
        /// Override the method load to load xml file
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public override T Load(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    return (T)xs.Deserialize(fs);
                }
                catch
                {
                    throw new Summer.Exception.IOException("Xml Load Failure", this.GetType());
                }
            }
        }
        /// <summary>
        /// Override save method to save xml file
        /// </summary>
        /// <param name="t"></param>
        /// <param name="path"></param>
        public override void Save(T t, string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                try
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    xs.Serialize(fs, t);
                }
                catch
                {
                    throw new Summer.Exception.IOException("Xml Save Failure", this.GetType());
                }
            }
        }

    }
}
